# -*- coding: utf-8 -*-
# @Time    : 2021/10/30 13:13
# @Author  : stephen
# @File    : classStudentSystemSerializer.py
from django.contrib.auth.models import User
from rest_framework import serializers

from student.models import Student, Classes


class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        exclude = ('create_time', 'update_time')
        extra_kwargs = {
            'age': {'min_value': 0, 'max_value': 200}
        }


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        exclude = ['id', 'password', 'user_permissions']


class ClassesSerializer(serializers.ModelSerializer):
    # student_set = StudentSerializer(many=True, read_only=True)
    member_detail = serializers.SerializerMethodField()

    def get_member_detail(self, classes):  # 获取当前model类classes的每个实例
        serializer = UserSerializer(classes.member.all(), many=True)
        data = {
            'student': [i for i in serializer.data if i['is_staff'] or 1 in i['groups']],
            'teacher': [i for i in serializer.data if 2 in i['groups']]
        }
        return data

    class Meta:
        model = Classes
        exclude = ('create_time', 'update_time', 'member')


class CreateUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'first_name', 'email')
        extra_kwargs = {
            'first_name': {
                'required': True
            },
            'email': {
                'required': True
            }
        }
